package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomizeException;
import com.heima.common.exception.CustomizeExceptionBuilder;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserService extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {
    @Transactional(rollbackFor = Exception.class)  //只有捕获到运行时异常时才会触发事务回滚
    @Override
    public ResponseResult login(AdUserDTO adUserDTO) {
        //1.检查参数
        if(StringUtils.isBlank(adUserDTO.getName()) || StringUtils.isBlank(adUserDTO.getPassword())){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        //2.根据用户名查询用户
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDTO.getName()));
        if(adUser == null){
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        //3.校验密码
        String password = adUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex((adUserDTO.getPassword() + adUser.getSalt()).getBytes());
        if (!digestPassword.equals(password)) {
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "登陆密码错误");
        }
        //4.检查用户状态
        if (!adUser.getStatus().equals(AdminConstants.USER_STATUS_OK)) {    //包装类比较是否相等使用 equals
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //5.修改登陆时间
        adUser.setLoginTime(new Date());
        this.updateById(adUser);
        //6.颁发 Token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //7.返回响应（令牌 +　用户信息）
        Map result = new HashMap<String, Object>();
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser, adUserVO);
        result.put("token", token);
        result.put("user", adUserVO);
        return ResponseResult.okResult(result);
    }
}
